package com.coding.service.impl;

import com.coding.base.pojo.BaseModel;
import com.coding.base.pojo.PageQueryModel;
import com.coding.base.util.DateUtil;
import com.coding.dao.NoteDao;
import com.coding.dao.UserDao;
import com.coding.pojo.Note;
import com.coding.pojo.User;
import com.coding.service.NoteService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @auther wangchenghao
 * @date 2020/9/26
 **/
@Service
public class NoteImpl implements NoteService {
    @Autowired
    NoteDao noteDao;
    @Autowired
    UserDao userDao;

    @Override
    public void addNote(int user_id, String noteName, String noteContent, String notePlace, BaseModel baseModel) throws Exception {
        User user = userDao.selectById(user_id);
        if (user == null) {
            baseModel.setFailure("未查询至该用户信息");
            return;
        }
        Note note = new Note();
        note.setUser(user);
        note.setNote_user_id(user_id);
        note.setNote_title(noteName);
        note.setNote_content(noteContent);
        note.setNote_place_name(notePlace);
        note.setNote_time(DateUtil.getStringDate());
        if (noteDao.insertSelective(note) == 1) {
            baseModel.setSucceed("新增笔记成功", note);
        } else {
            baseModel.setFailure("新增笔记失败", note);
        }
    }

    @Override
    public void selectNote(int note_id, BaseModel baseModel) throws Exception {
        Note note = noteDao.selectByPrimaryKey(note_id);
        if (note != null) {
            baseModel.setSucceed("查询帖子成功", note);
        } else {
            baseModel.setFailure("查询帖子失败");
        }

    }

    @Override
    public void selectByUser(int user_id, PageQueryModel pageQueryModel, BaseModel baseModel) throws Exception {
        User user = userDao.selectById(user_id);
        if (user == null) {
            baseModel.setFailure("未查询至该用户信息");
            return;
        }
        PageHelper.startPage(pageQueryModel.getPage(), pageQueryModel.getSize());
        List<Note> noteList=noteDao.selectByUserId(user_id);
        PageInfo pageInfo = new PageInfo(noteList);
        noteList = pageInfo.getList();
        if (noteList.size() == 0) {
            if (pageInfo.getPageNum() > 1) {
                baseModel.setFailure("已经没有下一页了");
            } else {
                baseModel.setOther(2, "没有符合条件的笔记");
            }
            return;
        }
        baseModel.setSucceed("查询成功，符合条件的笔记共" + noteList.size() + "条", noteList);
    }
}
